import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

interface SensorDataItem {
  id: string
  name: string
  value: number
  timestamp: string
}

interface SensorResponse {
  code: number
  message: string
  data: SensorDataItem[]
}

interface SensorData {
  airTemperature?: number    // 空气温度
  airHumidity?: number      // 空气相对湿度
  soilTemperature?: number   // 土壤温度
  soilPH?: number           // 土壤PH值
  soilNitrogen?: number     // 土壤氮含量
  soilPhosphorus?: number   // 土壤磷含量
  soilPotassium?: number    // 土壤钾含量
  timestamp?: string        // 时间戳
}

interface HistoryData {
  airTemperature: { value: number, timestamp: string }[]
  soilTemperature: { value: number, timestamp: string }[]
  airHumidity: { value: number, timestamp: string }[]
}

// 传感器ID映射
const SENSOR_IDS = {
  AIR_TEMP: '327061375295689611',    // 空气温度传感器
  AIR_HUMIDITY: '327061375295689612', // 空气相对湿度传感器
  SOIL_TEMP: '327061375295689614',    // 土壤温度传感器
  SOIL_PH: '327061375295689606',      // 土壤PH值传感器
  SOIL_N: '327061375295689607',       // 土壤氮含量传感器
  SOIL_P: '327061375295689608',       // 土壤磷含量传感器
  SOIL_K: '327061375295689609'        // 土壤钾含量传感器
}

// 辅助函数：获取北京时间字符串
function getBeiJingTime(date: Date): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
}

export const useSensorStore = defineStore('sensor', () => {
  const router = useRouter()
  const sensorData = ref<SensorData>({})
  const historyData = ref<HistoryData>({
    airTemperature: [],
    soilTemperature: [],
    airHumidity: []
  })
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 获取最新传感器数据
  const fetchLatestData = async () => {
    loading.value = true
    error.value = null

    try {
      // 获取认证 token
      const token = localStorage.getItem('token')
      if (!token) {
        console.error('未登录或token已失效')
        throw new Error('未登录或token已失效')
      }

      const response = await fetch('/api/sensor/data', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })

      if (!response.ok) {
        if (response.status === 401 || response.status === 403) {
          console.error('登录已过期，请重新登录')
          localStorage.removeItem('token')
          localStorage.removeItem('isLogin')
          throw new Error('登录已过期，请重新登录')
        }
        throw new Error(`获取数据失败: ${response.status}`)
      }

      const result = await response.json()
      
      // 处理传感器数据
      const newData: SensorData = {}
      if (result.code === 200 && result.data && Array.isArray(result.data)) {
        result.data.forEach((item: SensorDataItem) => {
          switch (item.id) {
            case SENSOR_IDS.AIR_TEMP:
              newData.airTemperature = item.value
              break
            case SENSOR_IDS.AIR_HUMIDITY:
              newData.airHumidity = item.value
              break
            case SENSOR_IDS.SOIL_TEMP:
              newData.soilTemperature = item.value
              break
            case SENSOR_IDS.SOIL_PH:
              newData.soilPH = item.value
              break
            case SENSOR_IDS.SOIL_N:
              newData.soilNitrogen = item.value
              break
            case SENSOR_IDS.SOIL_P:
              newData.soilPhosphorus = item.value
              break
            case SENSOR_IDS.SOIL_K:
              newData.soilPotassium = item.value
              break
          }
        })

        newData.timestamp = new Date().toISOString()
        sensorData.value = newData
      } else {
        throw new Error(result.message || '获取数据失败')
      }
    } catch (e) {
      console.error('获取传感器数据错误:', e)
      error.value = e instanceof Error ? e.message : '获取传感器数据失败'
    } finally {
      loading.value = false
    }
  }

  // 获取指定时间范围的历史数据
  const fetchWeekData = async () => {
    loading.value = true
    error.value = null

    try {
      // 获取认证 token
      const token = localStorage.getItem('token')
      if (!token) {
        console.error('未登录或token已失效')
        throw new Error('未登录或token已失效')
      }

      // 计算时间范围
      const endTime = new Date()
      const startTime = new Date(endTime.getTime() - 7 * 24 * 60 * 60 * 1000)

      const response = await fetch(`/api/sensor/history/range?startTime=${startTime.toISOString()}&endTime=${endTime.toISOString()}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })

      if (!response.ok) {
        if (response.status === 401 || response.status === 403) {
          console.error('登录已过期，请重新登录')
          localStorage.removeItem('token')
          localStorage.removeItem('isLogin')
          throw new Error('登录已过期，请重新登录')
        }
        throw new Error(`获取历史数据失败: ${response.status}`)
      }

      const data = await response.json()
      if (data.code === 200 && data.data) {
        // 重置历史数据
        historyData.value = {
          airTemperature: [],
          soilTemperature: [],
          airHumidity: []
        }

        // 按时间戳排序（后端已排序，这里以防万一）
        data.data.sort((a: SensorDataItem, b: SensorDataItem) => 
          new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
        )
        
        // 按传感器ID分组处理数据
        data.data.forEach((item: SensorDataItem) => {
          switch (item.id) {
            case SENSOR_IDS.AIR_TEMP:
              historyData.value.airTemperature.push({
                value: item.value,
                timestamp: item.timestamp
              })
              break
            case SENSOR_IDS.SOIL_TEMP:
              historyData.value.soilTemperature.push({
                value: item.value,
                timestamp: item.timestamp
              })
              break
          }
        })

        // 如果没有数据，确保是空数组
        if (historyData.value.airTemperature.length === 0) {
          historyData.value.airTemperature = []
        }
        if (historyData.value.soilTemperature.length === 0) {
          historyData.value.soilTemperature = []
        }
      } else {
        throw new Error(data.message || '获取历史数据失败')
      }
    } catch (e) {
      console.error('获取历史数据错误:', e)
      error.value = e instanceof Error ? e.message : '获取历史数据失败'
      // 发生错误时初始化为空数组
      historyData.value = {
        airTemperature: [],
        soilTemperature: [],
        airHumidity: []
      }
    } finally {
      loading.value = false
    }
  }

  return {
    sensorData,
    historyData,
    loading,
    error,
    fetchLatestData,
    fetchWeekData
  }
}) 